/*eslint-disable*/
// @ts-nocheck

import { Ref } from 'vue';
import {
  defined,
  SceneTransforms,
  ScreenSpaceEventHandler,
  ScreenSpaceEventType,
  Viewer,
} from '@space8/czm-plugin';
import { Channel } from '@/components/GlobalCesium/src/type';

export function useChannelPopup(
  show: Ref<boolean>,
  left: Ref<number>,
  top: Ref<number>,
  popupData: Channel,
  viewer: Viewer,
) {
  let position = null;

  function registerChannelClick() {
    const screenSpaceEventHandler = new ScreenSpaceEventHandler(viewer.canvas);
    screenSpaceEventHandler.setInputAction((clickEvent: any) => {
      const pickObject = viewer.scene.pick(clickEvent.position);
      if (
        defined(pickObject) &&
        defined(pickObject.id) &&
        defined(pickObject.id.type) &&
        (pickObject.id.type === 'qudao' || pickObject.id.type === 'shifanqu') &&
        defined(pickObject.id.polyline)
      ) {
        const pickPosition = viewer.scene.globe.pick(
          viewer.camera.getPickRay(clickEvent.position),
          viewer.scene,
        );
        viewer.scene.clampToHeightMostDetailed([pickPosition]).then((res) => {
          position = res[0] === undefined ? pickPosition : res[0];
        });
        const properties = pickObject.id.properties;
        popupData.name = properties.o_name;
        popupData.level = +properties['级别'];
        popupData.length = properties['干渠长'];
        popupData.flow = properties['流量'];
        popupData.width = properties['宽度'];
        popupData.depth = properties['深度'];
        popupData.slope = properties['纵坡'];
        show.value = true;
      } else {
        closeChannelWindow();
      }
    }, ScreenSpaceEventType.LEFT_CLICK);

    viewer.scene.preRender.addEventListener(() => {
      if (position && show.value) {
        const coordinates = SceneTransforms.worldToWindowCoordinates(viewer.scene, position);
        if (coordinates) {
          left.value = coordinates.x;
          top.value = coordinates.y;
        }
      }
    });
  }

  function closeChannelWindow() {
    show.value = false;
    position = null;
  }

  return {
    registerChannelClick,
    closeChannelWindow,
  };
}
